package com.kfm.wiki.controller;

import com.github.pagehelper.PageInfo;
import com.kfm.wiki.entity.User;
import com.kfm.wiki.ex.BussinessException;
import com.kfm.wiki.service.UserService;
import com.kfm.wiki.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public R list(@RequestParam(value = "current", defaultValue = "1") Integer current
            ,@RequestParam(value = "pageSize", defaultValue = "2") Integer pageSize,
                  User user){
        PageInfo<User> list = userService.list(current, pageSize, user);
//        PageInfo<User> list = userService.list(current, pageSize, user);
        return R.ok(list);
    }

    @PostMapping
    public R save(@RequestBody @Validated User user, BindingResult result){
        if (result.hasErrors()){
            throw new BussinessException(result.getFieldError().getDefaultMessage());
        }
        userService.save(user);
        return R.ok();
    }

    @PostMapping("/reset")
    public R resetPassword(@RequestBody User user){
        userService.save(user);
        return R.ok();
    }


    @DeleteMapping("/{id}")
    public R delete(@PathVariable("id") Long id){
        userService.removeById(id);
        return R.ok();
    }
}
